package com.nulldev.util.web.HttpServer3.extensions.nCaptcha.noscript_frontend;

import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.data.Sets.DataSet;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.nCaptcha;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.Captcha;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.user.User;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.util.CaptchaFallbackLocale;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.util.UUIDCookieLoader;
import com.nulldev.util.web.HttpServer3.legacyPages.v1.RequestType;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.nTube.util.NTubeUtils;

public class ChallengeGeneratorPage extends HttpPage3 {

	private static final String PAYLOAD = FileUtil.getResourceAsString(NoScriptFrontendResource.class, "iframe.html");

	public ChallengeGeneratorPage() {
		super("/captcha/challenge");
	}

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		if (request.getType() != RequestType.GET)
			return new Response(400);

		final User user = UUIDCookieLoader.userFromRequest(request);
		if (user == null) {
			return new Response(403);
		}

		if (user.isNotBot()) {
			final Captcha c = nCaptcha.randomCaptcha(user);
			final DataSet<String, String[]> b64 = c.generateBase64Image(user.getLevel(), request);
			user.setExpectedResults(b64.getB());

			return new Response(200, createStream(PAYLOAD
					/* */
					.replace("$U0", b64.getA())
					/* */
					.replace("$U1", CaptchaFallbackLocale.get(c.getType()))));
		} else {
			final String _intUrl;
			final String _hdr = request.header("Host", "");
			if (!StringsUtil.isZeroLengthOrNull(_hdr)) {
				if (NTubeUtils.wasOriginHTTPS(request)) {
					_intUrl = "https://" + _hdr;
				} else {
					_intUrl = "http://" + _hdr;
				}
			} else {
				_intUrl = _hdr;
			}

			return new Response(302, blankStream()).header("Location", _intUrl + "/captcha/challenge-cooldown");
		}
	}

}
